class Solution {
    public String tree2str(TreeNode root) {
        StringBuffer str = new StringBuffer();
        tree2strChild(root,str);
        return str.toString();
    }

    private void tree2strChild(TreeNode t,StringBuffer str) {
        if(t == null) return;

        str.append(t.val);

        if(t.left!=null) {
            str.append("(");
            tree2strChild(t.left,str);
            str.append(")");
        }else {
            if(t.right==null) {
                return;
            }else {
                str.append("()");
            }
        }

        if(t.right!=null) {
            str.append("(");
            tree2strChild(t.right,str);
            str.append(")");
        }else {
            return;
        }
    }
}